<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/base.js"></script>

</head>
<body>
<img id="iconImage" height="100px" width="100px" style="border-style: solid;border-color: #000000;border-width: 1px"/>
<br>
<input id="icon" type="file"/>
<br>
<button onclick="onUploadClick();">点击上传头像</button>
<script>
    let inputIcon=document.getElementById("icon");
    inputIcon.onchange=function(){
        handleFile(inputIcon.files);
    };
    function handleFile(files){
        if(files.length>1){
            alert("最多只能选择一个文件");
            return ;
        }
        if(files[0]){
            //将文件生成url
            let srcValue=window.URL.createObjectURL(files[0]);
            //选择完图片后立即在页面上预览
            document.getElementById("iconImage").src=srcValue;
            readAsDataUrl();
        }
    }
    let base64;
    function readAsDataUrl(){
        if(typeof FileReader=="undefined"){
            alert("请使用最新的Chrome浏览器");
            return false;
        }
        let file=document.getElementById("icon").files[0];
        let reader=new FileReader();
        reader.onload=function(e){
            base64=this.result;
            console.info(base64);
            base64=base64.substring(base64.indexOf(",")+1);
        };
        reader.readAsDataURL(file);
    }
    function onUploadClick() {
        //请求更新头像
        let url="http://localhost:9001/qf/user/icon";
        let method="post";
        let requestJson={};
        requestJson.base64=base64;
        $.rest(method,url,requestJson,function(r){
            if(r.ok){
                alert("更新成功");
            }
        });
    }
</script>
</body>
</html>